<template>
	<div class="animated bounceInDown sele_none">
		<el-row :gutter="16">
			<el-col :span="14">
				<div class="separate_page area1">
					<div class="dflex_sb">
						<h3>日/月订单数</h3>
						<div>
							<el-button class="echarts-btn" size="mini" :class="{ active: orderCutBtn == '日' }" @click="orderDay" round>日</el-button>
							<el-button class="echarts-btn" size="mini" :class="{ active: orderCutBtn == '月' }" @click="orderMonth" round>月</el-button>
						</div>
					</div>
					<div id="order" class="h100 animated bounceInDown"></div>
				</div>
			</el-col>
			<el-col :span="10">
				<div class="separate_page area1">
					<h3>订单状态</h3>
					<div id="orderSta" class="h100"></div>
				</div>
			</el-col>
		</el-row>
		<el-row :gutter="16">
			<el-col :span="5">
				<div class="separate_page margin_b_0 area2">
					<h3>订单统计</h3>
					<div v-loading="orderLoading" element-loading-background="rgba(255, 255, 255, 0.8)" class="margin_t_30 pos_r animated bounceInDown">
						<div class="order margin_b_40 dflex_vertical_c">
							<div class="order_circle">总</div>
							<div class="pos_a order_right">
								<div class="order_title">总单数</div>
								<v-countup class="order_data" start-value="0" :end-value="orderSta.order_cnt"></v-countup>
							</div>
						</div>
						<div class="order margin_b_40 dflex_vertical_c">
							<div class="order_circle">单</div>
							<div class="pos_a order_right">
								<div class="order_title">客单价</div>
								<v-countup class="order_data price" start-value="0" :end-value="orderSta.average_cnt" :decimals="2"></v-countup>
							</div>
						</div>
						<div class="order margin_b_40 dflex_vertical_c">
							<div class="order_circle">支</div>
							<div class="pos_a order_right">
								<div class="order_title">支付数</div>
								<v-countup class="order_data" start-value="0" :end-value="orderSta.pay_cnt"></v-countup>
							</div>
						</div>
						<div class="order margin_b_40 dflex_vertical_c">
							<div class="order_circle">金</div>
							<div class="pos_a order_right">
								<div class="order_title">付款金额</div>
								<v-countup class="order_data ellipsis price" start-value="0" :end-value="orderSta.pay_money" :decimals="2"></v-countup>
							</div>
						</div>
						<div class="order margin_b_40 dflex_vertical_c">
							<div class="order_circle">退</div>
							<div class="pos_a order_right">
								<div class="order_title">退款数</div>
								<v-countup class="order_data" start-value="0" :end-value="orderSta.refund_cnt"></v-countup>
							</div>
						</div>
					</div>
				</div>
			</el-col>
			<el-col :span="19">
				<div class="separate_page margin_b_0 area2">
					<div class="dflex_sb">
						<h3>日/月退款数</h3>
						<div>
							<el-button class="echarts-btn" size="mini" :class="{ active: refundCutBtn == '日' }" @click="refundDay" round>日</el-button>
							<el-button class="echarts-btn" size="mini" :class="{ active: refundCutBtn == '月' }" @click="refundMonth" round>月</el-button>
						</div>
					</div>
					<div id="member" class="h100"></div>
				</div>
			</el-col>
		</el-row>
		<el-backtop target="uni-page-body"></el-backtop>
	</div>
</template>

<script>
import vCountup from 'vue-countupjs';
import echarts from 'echarts';
export default {
	components: { vCountup },
	data() {
		return {
			orderCutBtn: '日',
			orderDom: null,
			orderOption: [],
			orderStaDom: null,
			orderStaOption: [],
			orderLoading: false,
			orderSta: {
				order_cnt: 0,
				average_cnt: 0,
				pay_cnt: 0,
				pay_money: 0,
				refund_cnt: 0
			},
			refundCutBtn: '日',
			refundDom: null,
			refundOption: []
		};
	},
	methods: {
		async orderDay() {
			this.orderCutBtn = '日';

			uni.setStorage({
				key: '__orderCutSta' + this.$route.path,
				data: this.orderCutBtn
			});

			this.orderDom.showLoading({
				text: '加载中 · · ·',
				color: '#ff6a6c',
				textColor: '#000',
				maskColor: 'rgba(255, 255, 255, 1)'
			});

			const res1 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.groupBy('dateToString(add(new Date(0),create_time),"%Y年%m月%d日","+0800") as time')
				.groupField('count(*) as order_cnt')
				.orderBy('time desc')
				.limit(30)
				.get();

			const res2 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id'),
					is_delete: 0,
					order_pay_state: '已付款'
				})
				.groupBy('dateToString(add(new Date(0),create_time),"%Y年%m月%d日","+0800") as time')
				.groupField('count(*) as pay_cnt, sum(order_actural_paid) as pay_money')
				.orderBy('time desc')
				.limit(30)
				.get();

			let res = {
				code: 0,
				datas: []
			};

			await Promise.all([res1, res2])
				.then(resData => {
					let data = {};
					resData[0].result.data.forEach(x => {
						data = {
							...x,
							...resData[1].result.data.find(p => p.time == x.time)
						};
						res.datas.push(data);
					});
				})
				.catch(err => {
					this.orderDom.hideLoading();
				});

			this.orderDom.hideLoading();

			this.orderOption.xAxis.data = [];
			this.orderOption.series[0].data = [];
			this.orderOption.series[1].data = [];

			let today;
			let todaystr;
			for (let i = 30; i >= 0; i--) {
				today = new Date();
				today.setTime(today.getTime() - 1000 * 60 * 60 * 24 * i);
				todaystr = today.format('yyyy年MM月dd日');

				let data = res.datas.find(x => x.time == todaystr) || {};

				this.orderOption.series[0].data.push({
					value: data.order_cnt || 0,
					name: todaystr
				});

				this.orderOption.series[1].data.push({
					value: data.pay_cnt || 0,
					money: (data.pay_money || 0) / 100
				});
				this.orderOption.xAxis.data.push({
					value: today.format('dd')
				});
			}

			this.orderDom.setOption(this.orderOption);
		},
		async orderMonth() {
			this.orderCutBtn = '月';

			uni.setStorage({
				key: '__orderCutSta' + this.$route.path,
				data: this.orderCutBtn
			});

			this.orderDom.showLoading({
				text: '加载中 · · ·',
				color: '#ff6a6c',
				textColor: '#000',
				maskColor: 'rgba(255, 255, 255, 1)'
			});

			const res1 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.groupBy('dateToString(add(new Date(0),create_time),"%Y年%m月","+0800") as time')
				.groupField('count(*) as order_cnt')
				.orderBy('time desc')
				.limit(12)
				.get();

			const res2 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id'),
					is_delete: 0,
					order_pay_state: '已付款'
				})
				.groupBy('dateToString(add(new Date(0),create_time),"%Y年%m月","+0800") as time')
				.groupField('count(*) as pay_cnt, sum(order_actural_paid) as pay_money')
				.orderBy('time desc')
				.limit(12)
				.get();

			let res = {
				code: 0,
				datas: []
			};

			await Promise.all([res1, res2])
				.then(resData => {
					let data = {};
					resData[0].result.data.forEach(x => {
						data = {
							...x,
							...resData[1].result.data.find(p => p.time == x.time)
						};
						res.datas.push(data);
					});
				})
				.catch(err => {
					this.orderDom.hideLoading();
				});

			this.orderDom.hideLoading();

			let data = {};
			resData[0].result.data.forEach(x => {
				data = {
					...x,
					...resData[1].result.data.find(p => p.time == x.time)
				};
				res.datas.push(data);
			});

			this.orderOption.xAxis.data = [];
			this.orderOption.series[0].data = [];
			this.orderOption.series[1].data = [];

			let today;
			let todaystr;
			for (let i = 11; i >= 0; i--) {
				today = new Date();
				today.setMonth(today.getMonth() - i);
				todaystr = today.format('yyyy年MM月');

				let data = res.datas.find(x => x.time == todaystr) || {};

				this.orderOption.series[0].data.push({
					value: data.order_cnt || 0,
					name: todaystr
				});

				this.orderOption.series[1].data.push({
					value: data.pay_cnt || 0,
					money: (data.pay_money || 0) / 100
				});
				this.orderOption.xAxis.data.push({
					value: today.format('MM')
				});
			}

			this.orderDom.setOption(this.orderOption);
		},
		orderCharts(callback) {
			this.orderDom = this.$echarts.init(document.getElementById('order'));

			this.orderOption = {
				backgroundColor: '#fff',
				grid: {
					top: '50px',
					bottom: '60px',
					left: '30px',
					right: '10px'
				},
				tooltip: {
					trigger: 'axis',
					label: {
						show: true
					},
					formatter: function(params) {
						let str = '';

						str += ' ' + params[0].data.name + '    ' + '\n';
						params.forEach(item => {
							if (item.seriesName === '订单数') {
								str += ' ' + item.seriesName + ': ' + item.data.value + '' + '\n';
							} else if (item.seriesName === '支付数') {
								str += ' ' + item.seriesName + ': ' + item.data.value + '' + '\n';
								str += ' ' + '支付金额' + ': ￥' + item.data.money + '   ';
							}
						});
						return str;
					}
				},
				legend: {
					data: ['订单数', '支付数'],
					top: '0%',
					textStyle: {
						color: '#000'
					}
				},
				xAxis: {
					axisLine: {
						show: false
					},
					splitLine: {
						show: false
					},
					axisTick: {
						show: true,
						alignWithLabel: true,
						lineStyle: {
							color: '#ccc'
						}
					},
					data: []
				},
				yAxis: {
					axisLine: {
						show: false
					},
					splitLine: {
						show: true,
						lineStyle: {
							color: 'rgba(0, 0, 0, 0.1)'
						}
					},
					axisTick: {
						show: false
					},
					splitArea: {
						show: true,
						areaStyle: {
							color: 'rgba(0, 0, 0, 0)'
						}
					}
				},
				series: [
					{
						smooth: true,
						name: '订单数',
						type: 'line',
						symbol: 'circle',
						symbolSize: 4,
						showSymbol: false,
						lineStyle: {
							width: 3,
							color: '#ff6a6c',
							shadowColor: 'rgba(255, 106, 108, 0.6)',
							shadowBlur: 10,
							shadowOffsetY: 20
						},
						itemStyle: {
							color: '#ff6a6c'
						},
						data: []
					},
					{
						smooth: true,
						name: '支付数',
						type: 'line',
						symbol: 'circle',
						symbolSize: 4,
						showSymbol: false,
						lineStyle: {
							width: 3,
							color: '#69b5ff',
							shadowColor: 'rgba(105, 181, 255, 0.6)',
							shadowBlur: 10,
							shadowOffsetY: 20
						},
						itemStyle: {
							color: '#69b5ff'
						},
						data: []
					}
				]
			};

			window.addEventListener('resize', () => {
				this.orderDom.resize();
			});

			if (typeof callback === 'function') {
				callback();
			}
		},
		async orderStaData() {
			this.orderStaDom.showLoading({
				text: '加载中 · · ·',
				color: '#ff6a6c',
				textColor: '#000',
				maskColor: 'rgba(255, 255, 255, 1)'
			});

			const res1 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.groupBy('order_pay_state as state')
				.groupField('count(*) as cnt')
				.get();

			const res2 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id')
				})
				.groupBy('state')
				.groupField('count(*) as cnt')
				.get();

			let pay = {
				code: 0,
				datas: []
			};

			let state = {
				code: 0,
				datas: []
			};

			await Promise.all([res1, res2])
				.then(resData => {
					resData[0].result.data.forEach(x => {
						pay.datas.push({
							cnt: x.cnt,
							state: x.state
						});
					});

					resData[1].result.data.forEach(x => {
						state.datas.push({
							cnt: x.cnt,
							state: x.state
						});
					});
				})
				.catch(err => {
					this.orderStaDom.hideLoading();
				});

			this.orderStaDom.hideLoading();

			if (pay.datas.length > 0) {
				pay.code = 200;
			}

			if (pay.code == 200) {
				pay.datas.forEach(x => {
					this.orderStaOption.series[0].data.push({
						value: x.cnt,
						name: x.state
					});
				});
			}

			if (state.datas.length > 0) {
				state.code = 200;
			}

			if (state.code == 200) {
				state.datas.forEach(x => {
					this.orderStaOption.series[1].data.push({
						value: x.cnt,
						name: x.state
					});
				});
			}

			this.orderStaDom.setOption(this.orderStaOption);
		},
		orderStaCharts(callback) {
			this.orderStaDom = this.$echarts.init(document.getElementById('orderSta'));

			this.orderStaOption = {
				backgroundColor: '#fff',
				color: [
					'#2ec7c9',
					'#b6a2de',
					'#5ab1ef',
					'#ffb980',
					'#d87a80',
					'#8d98b3',
					'#FFEA01',
					'#B8D07C',
					'#fca4bb',
					'#dc69aa',
					'#07a2a4',
					'#9a7fd1',
					'#588dd5',
					'#f5994e',
					'#c05050',
					'#59678c',
					'#c9ab00',
					'#7eb00a',
					'#6f5553',
					'#c14089'
				],
				tooltip: {
					trigger: 'item',
					formatter: ' {a} \n {b}: {c}   '
				},
				series: [
					{
						name: '支付状态',
						type: 'pie',
						radius: ['0', '36%'],
						itemStyle: {
							normal: {
								borderColor: 'rgba(0, 0, 0, 0)'
							}
						},
						label: {
							position: 'inside'
						},
						data: []
					},
					{
						name: '订单状态',
						type: 'pie',
						radius: ['45%', '55%'],
						labelLine: {
							length2: 90,
							lineStyle: {
								color: 'rgba(0, 0, 0, 0.1)'
							}
						},
						label: {
							formatter: params => {
								return '{icon|●}{name|' + params.name + '}{value|' + params.value + '}';
							},
							padding: [0, -70, 16, -70],
							rich: {
								color: '#333',
								icon: {
									fontSize: 16
								},
								name: {
									fontSize: 14,
									padding: [0, 5, 0, 5],
									color: '#666666'
								},
								percent: {
									color: '#333',
									padding: [0, 5, 0, 0]
								},
								value: {
									fontSize: 16,
									color: '#333333'
								}
							}
						},
						data: []
					}
				]
			};

			window.addEventListener('resize', () => {
				this.orderStaDom.resize();
			});

			if (typeof callback === 'function') {
				callback();
			}
		},
		async getOrder() {
			this.orderLoading = true;
			const res1 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id'),
					is_delete: 0
				})
				.groupBy('is_delete')
				.groupField('count(*) as order_cnt')
				.get();

			const res2 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id'),
					is_delete: 0,
					order_pay_state: '已付款'
				})
				.groupBy('is_delete')
				.groupField('count(*) as pay_cnt, sum(order_actural_paid) as pay_money')
				.get();

			const res3 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id'),
					is_delete: 0,
					order_refund_state: '已退款'
				})
				.groupBy('is_delete')
				.groupField('count(*) as refund_cnt')
				.get();

			await Promise.all([res1, res2, res3])
				.then(res => {
					this.orderSta = {
						...this.orderSta,
						...res[0].result.data[0],
						...res[1].result.data[0],
						...res[2].result.data[0]
					};
				})
				.catch(err => {
					this.orderLoading = false;
				});

			this.orderLoading = false;

			this.orderSta.average_cnt = this.orderSta.pay_money / 100 / this.orderSta.pay_cnt || 0;
			this.orderSta.pay_money = this.orderSta.pay_money / 100;
		},
		async refundDay() {
			this.refundCutBtn = '日';

			uni.setStorage({
				key: '__refundCutSta' + this.$route.path,
				data: this.refundCutBtn
			});

			this.refundDom.showLoading({
				text: '加载中 · · ·',
				color: '#ff6a6c',
				textColor: '#000',
				maskColor: 'rgba(255, 255, 255, 1)'
			});

			const res1 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id'),
					order_refund_state: '已退款'
				})
				.groupBy('dateToString(add(new Date(0),create_time),"%Y年%m月%d日","+0800") as time')
				.groupField('count(*) as refund_cnt')
				.orderBy('time desc')
				.limit(30)
				.get();

			let res = {
				code: 0,
				datas: []
			};

			await Promise.all([res1])
				.then(resData => {
					res.datas = resData[0].result.data || [];
				})
				.catch(err => {
					this.refundDom.hideLoading();
				});

			this.refundDom.hideLoading();

			this.refundOption.xAxis.data = [];
			this.refundOption.series[0].data = [];

			let today;
			let todaystr;
			for (let i = 30; i >= 0; i--) {
				today = new Date();
				today.setTime(today.getTime() - 1000 * 60 * 60 * 24 * i);
				todaystr = today.format('yyyy年MM月dd日');

				let data = res.datas.find(x => x.time == todaystr) || {};

				this.refundOption.series[0].data.push({
					value: data.refund_cnt || 0,
					name: todaystr
				});
				this.refundOption.xAxis.data.push({
					value: today.format('dd')
				});
			}

			this.refundDom.setOption(this.refundOption);
		},
		async refundMonth() {
			this.refundCutBtn = '月';

			uni.setStorage({
				key: '__refundCutSta' + this.$route.path,
				data: this.refundCutBtn
			});

			this.refundDom.showLoading({
				text: '加载中 · · ·',
				color: '#ff6a6c',
				textColor: '#000',
				maskColor: 'rgba(255, 255, 255, 1)'
			});

			const res1 = this.$db['wmzmall-order']
				.collection()
				.action('base-where-action')
				.where({
					shop_id:uni.getStorageSync('wmzadmin_user_shop_id'),
					order_refund_state: '已退款'
				})
				.groupBy('dateToString(add(new Date(0),create_time),"%Y年%m月","+0800") as time')
				.groupField('count(*) as refund_cnt')
				.orderBy('time desc')
				.limit(12)
				.get();

			let res = {
				code: 0,
				datas: []
			};

			await Promise.all([res1])
				.then(resData => {
					res.datas = resData[0].result.data || [];
				})
				.catch(err => {
					this.refundDom.hideLoading();
				});

			this.refundDom.hideLoading();

			this.refundOption.xAxis.data = [];
			this.refundOption.series[0].data = [];

			let today;
			let todaystr;
			for (let i = 11; i >= 0; i--) {
				today = new Date();
				today.setDate(1);
				today.setMonth(today.getMonth() - i);
				todaystr = today.format('yyyy年MM月');

				let data = res.datas.find(x => x.time == todaystr) || {};

				this.refundOption.series[0].data.push({
					value: data.refund_cnt || 0,
					name: todaystr
				});
				this.refundOption.xAxis.data.push({
					value: today.format('MM')
				});
			}

			this.refundDom.setOption(this.refundOption);
		},
		refundCharts(callback) {
			this.refundDom = this.$echarts.init(document.getElementById('member'));

			this.refundOption = {
				backgroundColor: '#FFF',
				grid: {
					top: '50px',
					bottom: '60px',
					left: '30px',
					right: '10px'
				},
				tooltip: {
					trigger: 'axis',
					label: {
						show: true
					},
					formatter: function(params) {
						let str = '';

						str += ' ' + params[0].data.name + '    ' + '\n';

						params.forEach(item => {
							str += ' ' + item.seriesName + ': ' + item.data.value;
						});
						return str;
					}
				},
				legend: {
					data: ['退款数'],
					top: '0%',
					textStyle: {
						color: '#000'
					}
				},
				xAxis: {
					axisLine: {
						show: false
					},
					splitLine: {
						show: false
					},
					axisTick: {
						show: true,
						alignWithLabel: true,
						lineStyle: {
							color: '#ccc'
						}
					},
					data: []
				},
				yAxis: {
					axisLine: {
						show: false
					},
					splitLine: {
						show: true,
						lineStyle: {
							color: 'rgba(0, 0, 0, 0.1)'
						}
					},
					axisTick: {
						show: false
					},
					splitArea: {
						show: true,
						areaStyle: {
							color: 'rgba(0, 0, 0, 0)'
						}
					}
				},
				series: [
					{
						smooth: true,
						name: '退款数',
						type: 'line',
						symbol: 'circle',
						symbolSize: 4,
						showSymbol: false,
						lineStyle: {
							width: 3,
							color: '#ff6a6c',
							shadowColor: 'rgba(255, 106, 108, 0.6)',
							shadowBlur: 10,
							shadowOffsetY: 20
						},
						itemStyle: {
							color: '#ff6a6c'
						},
						data: []
					}
				]
			};

			window.addEventListener('resize', () => {
				this.refundDom.resize();
			});

			if (typeof callback === 'function') {
				callback();
			}
		}
	},
	created() {
		this.getOrder();
	},
	mounted() {
		this.orderCharts(() => {
			const orderSta = uni.getStorageSync('__orderCutSta' + this.$route.path) || '日';
			if (orderSta == '日') {
				this.orderDay();
			} else {
				this.orderMonth();
			}
		});

		this.orderStaCharts(() => {
			this.orderStaData();
		});

		this.refundCharts(() => {
			const refundSta = uni.getStorageSync('__refundCutSta' + this.$route.path) || '日';
			if (refundSta == '日') {
				this.refundDay();
			} else {
				this.refundMonth();
			}
		});

		this.$nextTick(() => {
			this.$api.scrollOnStorage('uni-page-body', this.$route.path);
		});

		this.$nextTick(() => {
			this.$api.scrollToStorage('uni-page-body', this.$route.path);
		});
	}
};
</script>

<style>
.order {
	cursor: pointer;
}

.order_circle {
	font-size: 18px;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	width: 56px;
	height: 56px;
	border-radius: 50%;
	margin-left: 10px;
	background-color: #ff6b6b;
	transition: transform 0.2s;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.order:nth-child(2) .order_circle {
	background-color: #7e6aff;
}

.order:nth-child(3) .order_circle {
	background-color: #69b5ff;
}

.order:nth-child(4) .order_circle {
	background-color: #ffa66a;
}

.order:nth-child(5) .order_circle {
	margin-bottom: 0;
	background-color: #b96bff;
}

.order_right {
	left: 90px;
}

.order_title {
	font-size: 13px;
}

.order_data {
	font-size: 22px;
}

.order:hover .order_circle {
	transform: scale(1.2);
}

.price {
	color: #000;
}

.area1 {
	height: 500px;
}

.area2 {
	height: 600px;
}
</style>
